package com.aote.expression.paramprocessor;

import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import com.aote.expression.Param;
import com.aote.util.SingleValueHelper;
import com.browsesoft.dbtools.DBTools;
import com.browsesoft.htmlcomponent.HTMLBasicComponent;
import com.browsesoft.tools.BSCalendar;
import com.browsesoft.user.User;

public class CaiNuanJiLimitProcessor implements ParamProcessor {

	// 采暖季限购气量
	public String process(Param param, Map attributes, User loginUser,
			HTMLBasicComponent component) throws NoFitValueException {
		// 检查气价类型月数设置表，如果改气价类型设置了限购月数，根据限购月数计算可购和已购气量
		String wallhangboiler = (String) attributes.get("f_wallhangboiler");
		if (wallhangboiler == null) {
			wallhangboiler = "无";
		}
		String priceType = (String) attributes.get("f_gaspricetype");
		int canBuyMons = getPriceTypeMons(priceType, wallhangboiler);
		String result = "";
		// 得到用户总可购买气量
		result = this.getUserGas(param, attributes);
		int onceGas = Integer.parseInt(result);
		// 如果设置了气价够买月数，可购气量=单次可购气量*设置的月数，
		// 计算出统计已购的开始日期
		String buiedStartDate = "";
		if (canBuyMons > 0) {
			onceGas = onceGas * canBuyMons;
			buiedStartDate = this.ZhouQiStartDate(canBuyMons);
		}

		// 减去本月内买了的气量
		int fee = getSumPayFee(attributes, buiedStartDate);
		int gas = onceGas - fee;
		if (gas < 0) {
			gas = 0;
		}
		result = gas + "";
		return result;
	}

	// 计算开始日期
	private String ZhouQiStartDate(int mons) {
		int startMonth = -1;
		startMonth = Math.round(((BSCalendar.now().getMonth() - 1) / mons))
				* mons + 1;
		String str = startMonth + "01";
		if (str.length() == 3) {
			str = "0" + str;
		}
		str = BSCalendar.now().getYear() + str;
		return str;
	}

	// 得到用户气量
	private String getUserGas(Param param, Map attributes) {
		String result = "";
		// 如果档案中有限购气量设置，采用档案中的
		String customgas = (String) attributes.get("f_customgas");
		// customgas = customgas.trim();
		if (customgas != null && !customgas.trim().equals("")) {
			int customGas = Integer.parseInt(customgas);
			return customGas + "";
		}
		// 用气性质
		String gastype = (String) param.getParams().get("gastype");
		gastype = (String) attributes.get(gastype);
		if (gastype != null && gastype.equals("非民用")) {
			// 额定流量
			String f_flownum = (String) attributes.get("f_flownum");
			String f_gaspricetype = (String) attributes.get("f_gaspricetype");
			result = getGSGas(f_flownum, f_gaspricetype);
			if (!result.equals("")) {
				return result;
			}
			System.out.println("---------后台没有设置此流量的额定范围!-----------");
		} else if (gastype.equals("民用")) {
			result = getMYGas(param, attributes) + "";
			return result;
		}
		return "0";
	}

	// 获得民用每月限购气量
	private int getMYGas(Param param, Map attributes) {
		// 单值（非采暖）
		String name = getSingleName(param, attributes);
		String fvalue = SingleValueHelper.getStringValue(name);
		int f = Integer.parseInt(fvalue);
		// 有壁挂炉
		String wallhangboiler = (String) attributes.get("f_wallhangboiler");
		if (wallhangboiler != null && wallhangboiler.equals("有")) {
			// 获取采暖期值
			String type = (String) param.getParams().get("type");
			String cnvalue = getWarmSeason(type);
			int c = Integer.parseInt(cnvalue);
			// 返回采暖期+非采暖期值
			return f + c;
		} else {
			return f;
		}
	}

	// 获取采暖季单值，不在采暖季，或者其他原因，不需要采暖季，返回0
	private String getWarmSeason(String type) {
		// 配置的不是采暖季，不做
		if (type == null || !type.equals("采暖季")) {
			return "0";
		}
		try {
			String now = BSCalendar.now().getMonth() + "-"
					+ BSCalendar.now().getDay();
			String sql = "select * from t_addons";
			String[][] result = DBTools.executeQueryWithTableHead(sql);
			List list = DBTools.arrayToHashtable(result);
			for (int i = 0; i < list.size(); i++) {
				Hashtable ht = (Hashtable) list.get(i);
				String start = (String) ht.get("startdate");
				String end = (String) ht.get("enddate");
				boolean flag = judeMonth(now, start, end);
				// 找到了采暖季限购设置
				if (flag) {
					// 返回采暖季值
					String value = (String) ht.get("gas");
					return value;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "0";
	}

	private int getSumPayFee(Map attribures, String buiedStartDate) {
		int result = 0;
		// 本月日期
		// String thismonth = (String) attribures.get("f_deliverydate");
		String thismonth = BSCalendar.now().toString("yyyy-mm-dd");
		String f_userid = (String) attribures.get("f_userid");
		String f_payfeetype = (String) attribures.get("f_payfeetype");
		// 如果计算出来有开始日期，采用计算出来的开始日期，否则，只统计当月已购
		String dateCond = "";
		if (!buiedStartDate.equals("")) {
			dateCond = " f_deliverydate >= '" + buiedStartDate + "'";
		} else {
			dateCond = " f_deliverydate like '" + thismonth + "%'";
		}
		if (thismonth != null) {
			thismonth = thismonth.substring(0, 7);
			String sql = "select id,f_pregas from t_SellingGas where "
					+ dateCond + " and f_payfeetype='" + f_payfeetype
					+ "' and f_payfeevalid='有效' and f_userid='" + f_userid
					+ "'";
			try {
				String[][] value = DBTools.executeQueryWithTableHead(sql);
				List list = DBTools.arrayToHashtable(value);
				for (int i = 0; i < list.size(); i++) {
					Hashtable ht = (Hashtable) list.get(i);
					String str = (String) ht.get("f_pregas");
					if (str != null) {
						result += Integer.parseInt(str);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	private String getSingleName(Param param, Map attribures) {
		Map map = param.getParams();
		// 取出单值
		String name = (String) map.get("name");
		if (name != null && !name.equals("")) {
			return name;
		}
		// 取出用户类型
		String field = (String) map.get("field");
		// 特殊字符拼接
		String str = (String) map.get("str");
		if (attribures.get(field) != null) {
			if (str != null) {
				return (String) attribures.get(field) + str;
			}
			return (String) attribures.get(field);
		} else {
			return "";
		}
	}

	// 判断大小
	private boolean judeMonth(String now, String start, String end) {
		String[] result = now.split("-");
		double now_month = Double.parseDouble(result[0]);
		double now_day = Double.parseDouble(result[1]);

		result = start.split("-");
		double start_month = Double.parseDouble(result[0]);
		double start_day = Double.parseDouble(result[1]);

		result = end.split("-");
		double end_month = Double.parseDouble(result[0]);
		double end_day = Double.parseDouble(result[1]);
		// 判断采暖季是否跨年了,
		// 如果结束月小于开始月则采暖季跨年了,
		if (end_month < start_month) {
			// 如果当前日期在前一年，则必须大于开始月
			if (now_month > start_month) {
				return true;
			}
			// 如果当前日期在第二年，则必须小于结束日期
			if (now_month < end_month) {
				return true;
			}
		}
		// 没跨年
		else {
			// 当前日期在设置日期内返回true
			if (now_month > start_month && now_month < end_month) {
				return true;
			}
			// 如果当前月等于开始和结束月，当前日必须在开始和结束日之间返回true
			if (now_month == start_month && now_month == end_month
					&& start_day < now_day && now_day <= end_day) {
				return true;
			}
		}
		// 如果当前月等于开始月，并且当前日大于开始日，返回true
		if (now_month == start_month && now_day >= start_day) {
			return true;
		}
		// 如果当前月等于结束月，并且当前日小于结束日，返回true
		if (now_month == end_month && now_day <= end_day) {
			return true;
		}
		return false;
	}

	/**
	 * 工商用户根据额定流量获得限购气量
	 */
	private String getGSGas(String f_flownum, String f_gaspricetype) {
		String result = "";
		String sql = "select f_fanwei,f_gscustomgas,id from t_gsxiangou";
		String[][] value;
		try {
			value = DBTools.executeQueryWithTableHead(sql);
			for (int i = 1; i < value.length; i++) {
				String flownum = value[i][0];
				if (flownum(f_flownum, flownum)) {
					// 如果在改流量下有气价类型限购，返还气价类型限购
					sql = "select f_limit from t_qijialimit where parentid='"
							+ value[i][2] + "' and f_gaspricetype='"
							+ f_gaspricetype + "'";
					String[][] value2 = DBTools.executeQueryWithTableHead(sql);
					if (value2.length > 1) {
						return value2[1][0];
					}
					return value[i][1];
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	// 判断用户流量是否在设置流量内，返回，此流量对应的限购
	private boolean flownum(String f_flownum, String flownum) {
		if (flownum.indexOf("-") != -1) {
			String[] value = flownum.split("-");
			double a = Double.parseDouble(value[0]);
			double b = Double.parseDouble(value[1]);
			double m = Double.parseDouble(f_flownum);
			if (a < m && m <= b) {
				return true;
			} else {
				return false;
			}
		}
		return false;
	}

	// 获取气价类型限购月数设置
	public int getPriceTypeMons(String priceType, String isbigua) {
		int result = -1;
		try {
			String sql = "select f_months from t_qijiaxiangouset where f_qijiatype='"
					+ priceType + "' and f_bigua='" + isbigua + "'";
			String[][] datas = DBTools.executeQueryWithTableHead(sql);
			if (datas.length > 1) {
				result = Integer.parseInt(datas[1][0]);
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return result;
	}
}
